package com.nengchuan.eic.nceconomy.controller;

import com.github.pagehelper.PageInfo;
import com.nengchuan.eic.nceconomy.constant.CommonConstant;
import com.nengchuan.eic.nceconomy.constant.SwFileComputeStatusEnum;
import com.nengchuan.eic.nceconomy.entity.dto.CloudFileCalculateDTO;
import com.nengchuan.eic.nceconomy.entity.dto.SwFilePageDTO;
import com.nengchuan.eic.nceconomy.entity.dto.SwFileSaveDTO;
import com.nengchuan.eic.nceconomy.entity.po.SwDirectory;
import com.nengchuan.eic.nceconomy.entity.po.SwFile;
import com.nengchuan.eic.nceconomy.entity.vo.OssFileReseponseVO;
import com.nengchuan.eic.nceconomy.entity.vo.SwFileStatusVO;
import com.nengchuan.eic.nceconomy.entity.vo.SwFileVO;
import com.nengchuan.eic.nceconomy.entity.vo.SwProjectDataVO;
import com.nengchuan.eic.nceconomy.fegin.BimplugFeignService;
import com.nengchuan.eic.nceconomy.fegin.ReportFeignService;
import com.nengchuan.eic.nceconomy.service.OssService;
import com.nengchuan.eic.nceconomy.service.SwDirectoryService;
import com.nengchuan.eic.nceconomy.service.SwFileService;
import com.nengchuan.eic.nceconomy.service.SwFileServiceImpl;
import com.nengchuan.eic.nceconomy.util.HttpUtils;
import com.nengchuan.model.model.WrappedResult;
import com.nengchuan.util.NullCheckUtils;
import com.nsc.boot.sdk.common.utils.AuthUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 三维测算文件相关Controller
 * @author: panwen
 * @create: 2020/05/25 15:06
 * @version：1.0.0
 */
@Api(value = "三维测算文件", tags = "三维测算文件")
@RestController
@RequestMapping("/sw_file")
@Validated
@Slf4j
public class SwFileController {

    @Autowired
    private SwFileService swFileService;

    @Autowired
    private SwDirectoryService swDirectoryService;

    @Autowired
    private ReportFeignService reportFeignService;

    @Autowired
    private BimplugFeignService bimplugFeignService;

    @Autowired
    private OssService ossService;
    private final static Logger logger = LoggerFactory.getLogger(SwFileServiceImpl.class);
    @ApiOperation("文件分页列表(分页+条件)")
    @GetMapping("/page")
    public WrappedResult<List<SwFileVO>> page(@Valid SwFilePageDTO dto) {
        List<SwFileVO> page = swFileService.page(dto);
        page.forEach(x->{
                if(x.getComputeStatus().equals(SwFileComputeStatusEnum.COMPUTEING.status)){
                    x.setQueryNum(x.getQueryNum() * 10>= 100 ? 90 : x.getQueryNum() * 10);
                }else {
                    x.setQueryNum(100);
                }
            });
        return WrappedResult.success(page);
    }

    @ApiOperation("获取文件汇总计算状态")
    @GetMapping("/cloud_file_status/{id}")
    public WrappedResult cloudFileStatus(@PathVariable("id") @NotNull @Min(1) Long id) {
        SwFile swFile = swFileService.getById(id);
        if (NullCheckUtils.isNull(swFile)) {
            return WrappedResult.fail("参数异常");
        }

        int computeStatus = swFile.getComputeStatus();
        int schedule = 0;

        SwFileStatusVO swFileStatusVO = SwFileStatusVO.builder().schedule(schedule).computeStatus(computeStatus).build();

        if (computeStatus == SwFileComputeStatusEnum.COMPUTEING.status) {
            schedule = swFile.getQueryNum() * 10;
            schedule = schedule >= 100 ? 90 : schedule;
            swFileStatusVO.setSchedule(schedule);
            swFileStatusVO.setSchedule(SwFileComputeStatusEnum.COMPUTEING.status);
        } else if (computeStatus == SwFileComputeStatusEnum.COMPUTE_SUCCESS.status) {

            swFileStatusVO.setSchedule(100);
            swFileStatusVO.setComputeStatus(SwFileComputeStatusEnum.COMPUTE_SUCCESS.status);
        }
        return WrappedResult.success(swFileStatusVO);
    }

    @ApiOperation("汇总计算列表数据查询")
    @GetMapping("/report_data")
    public WrappedResult getReportData(@RequestParam("id") Long id, @RequestParam("matchType") Integer matchType) {
        SwFile swFile = swFileService.getById(id);
        if (NullCheckUtils.isNull(swFile)) {
            return WrappedResult.fail("参数异常");
        }

        //查询清单与定额的数据
        WrappedResult<List<SwProjectDataVO>> result = bimplugFeignService.dwReport(swFile.getId(), swFile.getProjectType(), matchType);

//        WrappedResult<List<SwProjectDataVO>> result = bimplugFeignService.dwReport(122L, 2, matchType);
        if (result!=null&&result.getCode().equals(0)) {
            List<SwProjectDataVO> list=new ArrayList<>();
            List<SwProjectDataVO> data = result.getData();
            data.forEach(x->generlProjectInfo(x, list));

            return WrappedResult.success(list);
        }
        return WrappedResult.fail();
    }

    private void generlProjectInfo(SwProjectDataVO vo, List<SwProjectDataVO> data) {
        if(CollectionUtils.isEmpty(vo.getChildren())){
            return;
        }
        data.add(vo);
        vo.getChildren().forEach(x->generlProjectInfo(x,data));
        vo.setChildren(null);
    }

    @ApiOperation("汇总计算")
    @GetMapping("/collect_compute/{id}")
    public WrappedResult collectCompute(@PathVariable("id") @NotNull @Min(1) Long id) throws Exception {
        SwFile swFile = swFileService.getById(id);
        if (NullCheckUtils.isNull(swFile)) {
            return WrappedResult.fail("参数异常");
        }

        //调用远程接口进行汇总计算
        WrappedResult result = reportFeignService.cloudFileCalculate(CloudFileCalculateDTO.builder().fileId(swFile.getId()).url(swFile.getOssUrl()).build());
        if (result != null && result.getCode() == 0) {
            swFile.setComputeStatus(SwFileComputeStatusEnum.COMPUTEING.status);
            swFileService.updateById(swFile);
            return WrappedResult.success();
        }
        return WrappedResult.fail();
    }

    @ApiOperation("新增或更新")
    @PostMapping("/save_or_update")
    public WrappedResult<Boolean> saveOrUpdate(@Valid SwFileSaveDTO dto) throws Exception {
        SwDirectory swDirectory = swDirectoryService.getById(dto.getDirectoryId());
        if (NullCheckUtils.isNull(swDirectory)) {
            return WrappedResult.fail("无dirId");
        }

        boolean status = swFileService.insertOrUpdate(dto);
        long userId = AuthUtil.getUserId();
        log.info("#saveOrUpdate# 正在进行三维测算文件{}; [swDirId:{},userId:{},status:{}]", HttpUtils.getOperType(dto.getId()), dto.getId(), userId, status);
        return WrappedResult.success(status);
    }

    @ApiOperation("添加gfc和xml文件 临时")
    @PostMapping("/update_gfc_xml")
    public WrappedResult<Long> temFile( MultipartFile file) throws Exception {
        if(file!=null){
            Long aLong = ossService.uploadByOss(file);
            OssFileReseponseVO ossFileReseponseVO = ossService.getFilesFromOssById(aLong).getData();
            if(file.getOriginalFilename().endsWith("xml")){
                CommonConstant.TEMFILE.put(1,ossFileReseponseVO.getUrl());
            }else {
                CommonConstant.TEMFILE.put(2,ossFileReseponseVO.getUrl());
            }
            return WrappedResult.success(aLong);
        }
        return WrappedResult.fail();
    }


    @ApiOperation("删除")
    @PostMapping("/remove/{id}")
    public WrappedResult<Boolean> remove(@PathVariable("id") @NotNull(message = "id不能为空") @Min(value = 1, message = "id不符合格式") Long id) {
        boolean status = swFileService.removeById(id);
        long userId = AuthUtil.getUserId();
        log.info("#saveOrUpdate# 正在进行三维测算文件DELETE; [swFileId:{},userId:{},status:{}]", id, userId, status);
        return WrappedResult.success(status);
    }
}
